<?php
abstract class AbstractValidator {

    protected $ArFields;
    protected $BoReturn;
    protected $ArErrors;
    private $Post;

    public function __construct($Post) {
        $this->BoReturn = true;
        $this->ArErrors = array();
        $this->ArFields = array();
        $this->Post = $Post;
        $this->generateFields();
    }

    private function generateFields() {
        foreach ($this->Post as $StField => $MxValue) {
            if( is_array($MxValue) ) {
                $this->generateSubFields($StField, $MxValue);
                continue;
            }
           $this->ArFields[$StField] = new Field($StField, $MxValue);
        }
    }

    private function generateSubFields($StIndex, Array $ArValue) {
        foreach($ArValue as $StField => $Value) {
            $this->ArFields[$StIndex][$StField] = new Field($StField, $Value);
        }
    }

    public function addRules($StName, Array $ArRules) {
        if( $this->fieldExists($StName) ) {
            foreach( $ArRules as $Rule ) {
                $this->addRule($StName, $Rule);
            }
        }
    }

    public function addRule($StName, Rule $Rule) {
        if( $this->fieldExists($StName) ) {
            $this->ArFields[$StName]->addRule($Rule);
        }
    }

    protected function fieldExists($StIndex, $StName = false) {
        return empty($StName) ? isset($this->ArFields[$StIndex]) : isset($this->ArFields[$StIndex][$StName]);
    }

    public abstract function validate();

    public function getFirstError() {
        return $this->ArErrors[0] ?: '';
    }

    public function getErrors() {
        return $this->ArErrors;
    }

}

?>
